//
//  DHDrawerViewController.m
//  DeepBreathing
//
//  Created by DreamHack on 15-12-15.
//  Copyright (c) 2015年 DreamHack. All rights reserved.
//

#import "DHDrawerViewController.h"

@interface DHDrawerViewController ()

@property (nonatomic, strong) UIViewController * mainViewController;
@property (nonatomic, strong) UIViewController * leftViewController;
@property (nonatomic, strong) UIViewController * rightViewController;

@property (nonatomic, strong) UIScreenEdgePanGestureRecognizer * gestureOfOpenningLeftDrawer;
@property (nonatomic, strong) UIView * maskView;

- (void)handleDrawerForLeft:(BOOL)isLeft open:(BOOL)isOpen;
- (void)initializeAppearance;
- (CGFloat)interpolateFrom:(CGFloat)from to:(CGFloat)to percent:(CGFloat)percent;

@end

static const CGFloat maskAlpha_ = 0.6f;
static const CGFloat leftScale_ = 0.8f;
static const CGFloat mainX_ = 300.f;

@implementation DHDrawerViewController

#pragma mark - initialize

- (instancetype)initWithMainController:(UIViewController *)mainViewController leftViewController:(UIViewController *)leftViewController rightViewController:(UIViewController *)rightViewController
{
    self = [super init];
    if (self) {
        self.mainViewController = mainViewController;
        self.leftViewController = leftViewController;
        self.rightViewController = rightViewController;
    }
    return self;
}

- (instancetype)initWithMainController:(UIViewController *)mainViewController leftViewController:(UIViewController *)leftViewController
{
    return [self initWithMainController:mainViewController leftViewController:leftViewController rightViewController:nil];
}

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeAppearance];
}

#pragma mark - private methods
- (void)initializeAppearance
{
    [self.view addGestureRecognizer:self.gestureOfOpenningLeftDrawer];
    // 加载左抽屉
    [self addChildViewController:self.leftViewController];
    [self.leftViewController didMoveToParentViewController:self];
    self.leftViewController.view.transform = CGAffineTransformMakeScale(leftScale_, leftScale_);
    
    if (self.rightViewController) {
        [self addChildViewController:self.rightViewController];
        [self.rightViewController didMoveToParentViewController:self];
        self.rightViewController.view.transform = CGAffineTransformMakeScale(leftScale_, leftScale_);
    }
    
    // 加载主控制器
    [self addChildViewController:self.mainViewController];
    [self.view addSubview:self.mainViewController.view];
    [self.mainViewController didMoveToParentViewController:self];
}

- (void)handleDrawerForLeft:(BOOL)isLeft open:(BOOL)isOpen
{
    CGRect frame;
    CGFloat scale;
    CGFloat alpha;
    void (^completionBlock)(BOOL) = nil;
    if (isLeft && isOpen) {
        // 打开左抽屉
        [self.view insertSubview:self.leftViewController.view belowSubview:self.mainViewController.view];
        [self.mainViewController.view addSubview:self.maskView];
        frame = CGRectMake(mainX_, 0, 375, 667);
        scale = 1;
        alpha = maskAlpha_;
    } else if (isLeft && !isOpen) {
        // 关闭左抽屉
        frame = self.view.bounds;
        scale = leftScale_;
        alpha = 0;
        completionBlock = ^(BOOL flag) {
            [self.leftViewController.view removeFromSuperview];
            [self.maskView removeFromSuperview];
        };
    } else if (!isLeft && isOpen) {
        // 打开右抽屉
        [self.view insertSubview:self.rightViewController.view belowSubview:self.mainViewController.view];
        [self.mainViewController.view addSubview:self.maskView];
        frame = CGRectMake(-mainX_, 0, 375, 667);
        scale = 1;
        alpha = 1;
        
    } else {
        // 关闭右抽屉
        frame = self.view.bounds;
        scale = leftScale_;
        alpha = 0;
        completionBlock = ^(BOOL flag) {
            [self.rightViewController.view removeFromSuperview];
            [self.maskView removeFromSuperview];
        };
    }

    [UIView animateWithDuration:0.4 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:15 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.mainViewController.view.frame = frame;
        self.leftViewController.view.transform = CGAffineTransformMakeScale(scale, scale);
        self.maskView.alpha = alpha;
    } completion:completionBlock];
    

}

// 线性插值
- (CGFloat)interpolateFrom:(CGFloat)from to:(CGFloat)to percent:(CGFloat)percent
{
    return from + (to - from) * percent;
}

#pragma mark - interface methods
- (void)openLeftDrawer
{
    [self handleDrawerForLeft:YES open:YES];
}

- (void)closeLeftDrawer
{
    [self handleDrawerForLeft:YES open:NO];
}

- (void)openRightDrawer
{
    [self handleDrawerForLeft:NO open:YES];
}

- (void)closeRightDrawer
{
    [self handleDrawerForLeft:NO open:NO];
}

#pragma mark - callback/action

- (void)respondsToGesture:(UIScreenEdgePanGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        [self.view insertSubview:self.leftViewController.view belowSubview:self.mainViewController.view];
        [self.mainViewController.view addSubview:self.maskView];
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gesture translationInView:gesture.view];
        if (translation.x > 0) {
            CGFloat percent = translation.x / 250.f;
            if (percent > 1) {
                percent = 1;
            }
            CGFloat scale = [self interpolateFrom:leftScale_ to:1 percent:percent];
            CGFloat x = [self interpolateFrom:0 to:mainX_ percent:percent];
            CGFloat alpha = [self interpolateFrom:0 to:maskAlpha_ percent:percent];
            self.maskView.alpha = alpha;
            self.leftViewController.view.transform = CGAffineTransformMakeScale(scale, scale);
            self.mainViewController.view.frame = CGRectMake(x, 0, 375, 667);
            
        }
    } else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {
        CGPoint velocity = [gesture velocityInView:gesture.view];
        if (velocity.x > 0) {
            [self openLeftDrawer];
        } else {
            [self closeLeftDrawer];
        }
    }
}

- (void)tapOnMask:(UITapGestureRecognizer *)gesture
{
    [self closeLeftDrawer];
}

#pragma mark - getter
- (UIScreenEdgePanGestureRecognizer *)gestureOfOpenningLeftDrawer
{
    if (!_gestureOfOpenningLeftDrawer) {
        _gestureOfOpenningLeftDrawer = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(respondsToGesture:)];
        _gestureOfOpenningLeftDrawer.edges = UIRectEdgeLeft;
    }
    return _gestureOfOpenningLeftDrawer;
}

- (UIView *)maskView
{
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, 375, 667-64)];
        _maskView.alpha = 0;
        _maskView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnMask:)]];
    }
    return _maskView;
}




@end
